<template>
  <div class="connect-knowledges-container">
    <div class="tree-actions">
      <el-button type="primary" size="small" @click="expandAll">全部展开</el-button>
      <el-button type="primary" size="small" @click="collapseAll">全部收起</el-button>
      <el-button type="primary" size="small" @click="showKnowledgeSelector(true)" :disabled="disabled">新增一级节点</el-button>
    </div>
    <el-tree
      ref="treeRef"
      v-model:checkedKeys="checkedKeys"
      :data="treeData"
      :props="defaultProps"
      :draggable="true"
      :allow-drop="allowDrop"
      :allow-drag="allowDrag"
      @node-drag-start="handleDragStart"
      @node-drag-enter="handleDragEnter"
      @node-drag-leave="handleDragLeave"
      @node-drag-over="handleDragOver"
      @node-drag-end="handleDragEnd"
      @node-drop="handleDrop"
      @node-expand="handleExpand"
      @node-collapse="handleCollapse"
      @check="handleCheck"
    >
      <template #default="{ node, data }">
        <div class="custom-tree-node">
          <!-- 节点内容区 -->
          <div class="node-content">
            <div class="node-label-container">
              <span v-if="!editingNodeId || editingNodeId !== data.id" @dblclick="startEditing(data.id)">{{ node.label }}</span>
              <el-input
                v-else
                v-model="editingText"
                size="small"
                @blur="finishEditing"
                @keyup.enter="finishEditing"
                ref="editInputRef"
                style="width: 200px;display: inline-block;"
              />
          </div>
          </div>
          <!-- 操作按钮区 -->
          <div class="node-actions">
            <el-button
              type="success"
              size="small"
              icon="Plus"
              @click.stop="showKnowledgeSelector(false, node, data)"
              title="新增子节点"
              :disabled="disabled"
            ></el-button>
            <el-button
              type="danger"
              size="small"
              icon="Delete"
              @click.stop="deleteNode(node, data)"
              title="删除节点"
              :disabled="disabled || !canDelete(data)"
            ></el-button>
          </div>
        </div>
      </template>
    </el-tree>

    <!-- 知识点选择弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      title="选择知识点"
      width="700px"
      :close-on-click-modal="false"
    >
      <!-- 搜索区域 -->
      <div class="search-container">
        <el-input
          v-model="searchForm.keyword"
          placeholder="请输入知识点名称搜索"
          clearable
          @input="handleSearch"
          prefix-icon="Search"
          style="margin-bottom: 16px;"
        />

      </div>

      <!-- 知识点列表 -->
      <div class="knowledge-list-container">
        <el-table
          v-loading="loading"
          :data="knowledgeList"
          border
          style="width: 100%"
          @row-click="selectKnowledge"
          :row-class-name="tableRowClassName"
        >
          <el-table-column prop="name" label="知识点名称" min-width="180" />

          <el-table-column label="操作" width="100" >
            <template #default="scope">
              <el-button type="primary" size="small" @click="selectKnowledge(scope.row)">选择</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 弹窗底部 -->
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmSelection" :disabled="!selectedKnowledge">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, watch } from 'vue'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import { Plus, Delete, Search } from '@element-plus/icons-vue'
import * as knowledgesApi from '@/api/knowledges' // 导入知识点API
import { id } from 'element-plus/es/locale/index.mjs'

// 树形引用
const treeRef = ref(null)

// 编辑状态相关
const editingNodeId = ref(null)
const editingText = ref('')
const editInputRef = ref(null)

// 选中的节点键
const checkedKeys = ref([])

// 弹窗相关状态
const dialogVisible = ref(false)
const isAddingRoot = ref(false) // 是否添加根节点
const currentParentNode = ref(null)
const currentParentData = ref(null)
const selectedKnowledge = ref(null)

// 搜索表单
const searchForm = reactive({
  keyword: '',
  subjectId: '',
  gradeId: ''
})

// 知识点列表
const knowledgeList = ref([])
const loading = ref(false)
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 学科和年级数据
const subjects = ref([
  { id: 1, name: '数学' },
  { id: 2, name: '英语' }
])

const grades = ref([
  { id: 1, name: '初一' },
  { id: 2, name: '初二' },
  { id: 3, name: '初三' },
  { id: 4, name: '高一' }
])

// 监听选中状态变化，通知父组件
watch(
  () => checkedKeys.value,
  (newValue) => {
    emit('update:checkedKeys', newValue)
  }
)

// 定义触发事件
const emit = defineEmits(['update:checkedKeys'])

// 接收父组件传入的数据
const props = defineProps({
  data: {
    type: Array,
    default: () => []
  },
  self: { // 自己的节点
    type: Object,
    default: () => {}
  },
  disabled: {
    type: Boolean,
    default: false
  }
})

// 树形数据
let treeData = ref([])

// 确保节点名称不为空
const sanitizeNodeNames = (nodes) => {
  return nodes.map(node => {
    // 如果节点名称为空，设置默认名称
    const sanitizedNode = {
      ...node,
      label: node.label || `未命名节点${Date.now() % 1000}`
    }
    // 递归处理子节点
    if (node.children && node.children.length > 0) {
      sanitizedNode.children = sanitizeNodeNames(node.children)
    }
    return sanitizedNode
  })
}

// 树形配置
const defaultProps = {
  children: 'children',
  label: 'label',
  isLeaf: (data) => !data.children || data.children.length === 0
}

// 展开所有节点
const expandAll = () => {
  treeRef.value.store._getAllNodes().forEach(node => {
    node.expand()
  })
}

// 折叠所有节点
const collapseAll = () => {
  treeRef.value.store._getAllNodes().forEach(node => {
    node.collapse()
  })
}

// 开始编辑节点
const startEditing = (id) => {
  // 禁用模式下不允许编辑
  if (props.disabled) {
    return
  }
  const node = findNodeById(treeData.value, id)
  if (node) {
    editingNodeId.value = id
    editingText.value = node.label
    // 延迟聚焦，确保输入框已渲染
    setTimeout(() => {
      if (editInputRef.value) {
        editInputRef.value.focus()
      }
    }, 100)
  }
}

// 完成编辑
const finishEditing = () => {
  if (editingNodeId.value !== null) {
    const node = findNodeById(treeData.value, editingNodeId.value)
    if (node && editingText.value.trim()) {
      node.label = editingText.value.trim()
      ElMessage.success('修改成功')
    } else if (!editingText.value.trim()) {
      ElMessage.warning('节点名称不能为空')
    }
    editingNodeId.value = null
  }
}

// 根据ID查找节点
const findNodeById = (nodes, id) => {
  for (const node of nodes) {
    if (node.id === id) {
      return node
    }
    if (node.children) {
      const result = findNodeById(node.children, id)
      if (result) {
        return result
      }
    }
  }
  return null
}

// 显示知识点选择弹窗
const showKnowledgeSelector = (isRoot = true, parentNode = null, parentData = null) => {
  isAddingRoot.value = isRoot
  currentParentNode.value = parentNode
  currentParentData.value = parentData
  selectedKnowledge.value = null
  searchForm.keyword = ''
  searchForm.subjectId = ''
  searchForm.gradeId = ''
  pagination.currentPage = 1
  knowledgeList.value = []
  dialogVisible.value = true
  // 初始化时加载数据
  setTimeout(() => {
    handleSearch()
  }, 100)
}

// 搜索知识点
const handleSearch = async () => {
  try {
    loading.value = true
    
    const requestParams = {
      name: searchForm.keyword,
      id: props.self.id
    }
    
    const response = await knowledgesApi.selectAssociateKnowledge(
      requestParams
    )


    
    if (response.code === 200 && response.data) {
      
      // 格式化返回的数据
      knowledgeList.value = response.data.map(item => {
  
        return {
          ...item,
        }
      })

    } else {
      ElMessage.error('获取知识点列表失败')
      knowledgeList.value = []

    }
  } catch (error) {
    ElMessage.error('获取知识点列表异常：' + error.message)
  } finally {
    loading.value = false
  }
}

// 选择知识点
const selectKnowledge = (row) => {
  selectedKnowledge.value = row
}

// 表格行样式
const tableRowClassName = ({ row }) => {
  return selectedKnowledge.value?.id === row.id ? 'row-selected' : ''
}

// 分页相关函数
const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.currentPage = 1
  handleSearch()
}

const handleCurrentChange = (current) => {
  pagination.currentPage = current
  handleSearch()
}

// 确认选择知识点
const confirmSelection = () => {
  if (!selectedKnowledge.value) {
    ElMessage.warning('请选择一个知识点')
    return
  }
 
  const knowledge = selectedKnowledge.value
  
  if (isAddingRoot.value) {
    // 添加一级节点
    addRootNodeFromKnowledge(knowledge)
  } else {
    // 添加子节点
    addChildFromKnowledge(currentParentNode.value, currentParentData.value, knowledge)
  }
  
  dialogVisible.value = false
}

// 从知识点添加一级节点
const addRootNodeFromKnowledge = (knowledge) => {
  const newNode = {
    ...knowledge,
    children: [],
    label: knowledge.name,
    knowledgeInfo: knowledge, // 存储完整的知识点信息
  }
  treeData.value.unshift(newNode)
  ElMessage.success('添加一级节点成功')
}

// 从知识点添加子节点
const addChildFromKnowledge = (node, data, knowledge) => {
  const newId = knowledge.id || Date.now()
  const newNode = {
    id: newId,
    label: knowledge.name,
    knowledgeInfo: knowledge, // 存储完整的知识点信息
    children: []
  }

  if (!data.children) {
    data.children = []
  }

  data.children.push(newNode)
  if (node) {
    node.expand()
  }
  ElMessage.success('添加子节点成功')
}

// 添加子节点（原函数，保留但改为调用弹窗）
const addChild = (node, data) => {
  showKnowledgeSelector(false, node, data)
}

// 判断是否可以删除节点
const canDelete = (data) => {
  // 根节点不能删除
  return !isRootNode(data)
}

// 判断是否是根节点
const isRootNode = (data) => {
  return treeData.value.some(item => item.id === data.id)
}

// 删除节点
const deleteNode = (node, data) => {
  if (!canDelete(data)) {
    ElMessage.warning('根节点不能删除')
    return
  }

  // 找到父节点
  const parentNode = findParentNode(treeData.value, data.id)
  if (parentNode) {
    parentNode.children = parentNode.children.filter(item => item.id !== data.id)
    ElMessage.success('删除成功')
  }
}

// 查找父节点
const findParentNode = (nodes, id) => {
  for (const node of nodes) {
    if (node.children && node.children.some(child => child.id === id)) {
      return node
    }
    if (node.children) {
      const result = findParentNode(node.children, id)
      if (result) {
        return result
      }
    }
  }
  return null
}

// 拖拽相关函数
const handleDragStart = (node, event) => {
  // console.log('drag start', node, event)
}

const handleDragEnter = (node, event) => {
  // console.log('drag enter', node, event)
}

const handleDragLeave = (node, event) => {
  // console.log('drag leave', node, event)
}

const handleDragOver = (node, event) => {
  // console.log('drag over', node, event)
}

const handleDragEnd = (node, event) => {
  // console.log('drag end', node, event)
}

const handleDrop = (draggingNode, dropNode, dropType, event) => {
  // 禁用模式下不允许拖拽
  if (props.disabled) {
    ElMessage.warning('禁用模式下不允许拖拽节点')
    return
  }
  
  // console.log('drop', draggingNode, dropNode, dropType, event)

  // 不允许拖到自己内部
  if (isDescendant(draggingNode.data, dropNode.data)) {
    ElMessage.warning('不允许将节点拖放到其子节点中')
    return
  }

  // 获取拖拽节点的数据
  const draggingData = { ...draggingNode.data }

  // 从原位置删除
  const parentNode = findParentNode(treeData.value, draggingData.id)
  if (parentNode) {
    parentNode.children = parentNode.children.filter(item => item.id !== draggingData.id)
  } else {
    // 如果是根节点
    treeData.value = treeData.value.filter(item => item.id !== draggingData.id)
  }

  // 添加到新位置
  if (dropType === 'before') {
    // 前
    const dropParent = findParentNode(treeData.value, dropNode.data.id) || treeData.value
    const index = Array.isArray(dropParent) ? dropParent.findIndex(item => item.id === dropNode.data.id) : dropParent.children.findIndex(item => item.id === dropNode.data.id)
    if (Array.isArray(dropParent)) {
      dropParent.splice(index, 0, draggingData)
    } else {
      dropParent.children.splice(index, 0, draggingData)
    }
  } else if (dropType === 'after') {
    // 后
    const dropParent = findParentNode(treeData.value, dropNode.data.id) || treeData.value
    const index = Array.isArray(dropParent) ? dropParent.findIndex(item => item.id === dropNode.data.id) : dropParent.children.findIndex(item => item.id === dropNode.data.id)
    if (Array.isArray(dropParent)) {
      dropParent.splice(index + 1, 0, draggingData)
    } else {
      dropParent.children.splice(index + 1, 0, draggingData)
    }
  } else {
    // 内
    if (!dropNode.data.children) {
      dropNode.data.children = []
    }
    dropNode.data.children.push(draggingData)
    dropNode.expand()
  }

  ElMessage.success('拖拽成功')
}

// 检查是否是子孙节点
const isDescendant = (ancestor, descendant) => {
  if (!ancestor.children) return false

  return ancestor.children.some(child => {
    if (child.id === descendant.id) return true
    return isDescendant(child, descendant)
  })
}

// 展开节点
const handleExpand = (node, data) => {
  // console.log('expand', node, data)
}

// 折叠节点
const handleCollapse = (node, data) => {
  // console.log('collapse', node, data)
}

// 选中节点
const handleCheck = (data, checked, indeterminate) => {
  // console.log('check', data, checked, indeterminate)
}

// 添加一级节点（原函数，保留但改为调用弹窗）
const addRootNode = (rootNodeName, nodeId) => {
  showKnowledgeSelector(true)
}

// 监听父组件数据变化
watch(
  () => props.data,
  (newData) => {
    // 确保所有节点都有非空名称
    const sanitizedData = sanitizeNodeNames([...newData])
    treeData.value = sanitizedData
  },
  { immediate: true }
)

// 监听父组件数据变化
watch(
  () => props.self,
  (newData) => {
    // 禁用模式下不自动添加节点
    if (props.disabled) {
      return
    }
    if (newData.id) {
      // 如果已有ID，不做处理
    } else if (newData.name) {
      addRootNode(newData.name)
    }
  },
  { immediate: true }
)

// 暴露方法给父组件
defineExpose({
  getCheckedNodes: () => checkedKeys.value,
  setCheckedKeys: (keys) => {
    checkedKeys.value = keys
  },
  expandAll,
  collapseAll,
  treeData,
})
</script>

<style>
.connect-knowledges-container .el-tree-node__content {
  height: auto !important;
}

/* 选中行样式 */
.row-selected {
  background-color: #ecf5ff !important;
}

/* 搜索区域样式 */
.search-container {
  padding: 16px 0;
  border-bottom: 1px solid #ebeef5;
}

/* 列表容器样式 */
.knowledge-list-container {
  max-height: 400px;
  overflow-y: auto;
}

/* 分页容器样式 */
.pagination-container {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}
</style>

<style scoped>
.connect-knowledges-container {
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 8px;
}

.tree-actions {
  margin-bottom: 16px;
  display: flex;
  gap: 10px;
}

.el-tree {
  width: 100%;
  overflow: visible; 
}

.el-tree-node {
  position: relative;
  z-index: 1;
}

.custom-tree-node {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: calc(100% - 20px);
  padding: 4px 15px;
  margin: 6px 0;
  border-radius: 4px;
  background-color: #ffffff;
  border: 1px solid #e6e6e6;
  transition: all 0.2s;
  box-sizing: border-box;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

.custom-tree-node:hover {
  background-color: #f0f7ff;
  border-color: #c9e2ff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

/* 调整编辑框样式 */
.custom-tree-node .el-input {
  width: 100%;
  max-width: 200px;
}

/* 确保树形结构缩进正确 */
.el-tree-node__children {
  padding-left: 30px; 
}

/* 覆盖Element Plus默认样式 */
.el-tree-node__content {
  height: auto !important;
  padding: 0 !important;
}

/* 确保展开/折叠图标位置正确 */
.el-tree-node__expand-icon {
  margin-right: 8px;
}

.node-content {
  display: flex;
  align-items: center;
  flex-grow: 1;
}

.node-label-container {
  margin-left: 8px;
  width: 240px;
}

.node-label {
  cursor: pointer;
}

.node-label:hover {
  color: #409eff;
  text-decoration: underline;
}

.node-actions {
  display: flex;
  gap: 4px;
}

:deep(.el-tree-node__content) {
  padding: 0;
}

:deep(.el-tree-node__expand-icon) {
  font-size: 16px;
}

:deep(.el-tree-node__checkbox) {
  margin-right: 8px;
}
</style>